<?php
class language_model extends CI_Model
{
    public $id;
    public $code;
    public $desc_en;
    public $desc_vi;

    public function get_elements()
    {
        $query = $this->db->query("SELECT * FROM language ORDER BY code ASC");
        return $this->to_domain_models($query->result());
    }

    public function get_element_by_id($id)
    {
        $query = $this->db->query("SELECT * FROM language WHERE id = ?",array($id));
        return $this->to_domain_model($query->row());
    }

    public function get_element_by_value($value)
    {
        $query = $this->db->query("SELECT * FROM language WHERE desc_en = ? OR desc_vi = ?",array($value,$value));
        return $this->to_domain_model($query->row());
    }

    // -------------------------------------------------------------------------------- PUBLIC PROPERTY

    public function get_description()
    {
        $lang = $this->session->userdata('lang');
        if($lang == 'en') return $this->desc_en;
        return $this->desc_vi;
    }

    // -------------------------------------------------------------------------------- PRIVATE METHOD

    // Private method
    public function __get($key)
    {
        if(method_exists($this,$MethodName='get_'.$key)) return $this->$MethodName();
        $CI =& get_instance();
        return $CI->$key;
    }

    // Private method
    public function to_domain_models($array)
    {
        $result = array();
        foreach($array as $item)
        {
            $result[] = $this->to_domain_model($item);
        }
        return $result;
    }

    // Private method
    public function to_domain_model($item)
    {
        $model = new language_model();
        $model->id = isset($item->id) ? $item->id : '' ;
        $model->code = isset($item->code) ? $item->code : '' ;
        $model->desc_en = isset($item->desc_en) ? $item->desc_en : '' ;
        $model->desc_vi = isset($item->desc_vi) ? $item->desc_vi : '' ;
        return $model;
    }
}